package com.qk.management.controller;

import com.qk.common.Result;
import com.qk.entity.Avatar;
import com.qk.common.constants.AvatarMessageConstants;
import com.qk.management.service.AvatarService;
import com.qk.management.service.AvatarCleanupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/avatars")
@Slf4j
public class AvatarController {

    @Autowired
    private AvatarService avatarService;
    
    @Autowired
    private AvatarCleanupService avatarCleanupService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/upload")
    public Result uploadAvatar(@RequestParam("file") MultipartFile file,
                               @RequestParam("userId") Long userId,
                               @RequestParam("fileMd5") String fileMd5) {
        log.info("Uploading avatar for user: {}, fileMd5: {}", userId, fileMd5);

        Avatar currentAvatar = avatarService.getCurrentAvatar(userId);
        if (currentAvatar != null && fileMd5.equals(currentAvatar.getFileMd5())) {
            return Result.error(AvatarMessageConstants.AVATAR_DUPLICATE_UPLOAD);
        }

        String lockKey = "avatar:upload:" + userId + ":" + fileMd5;
        Boolean locked = redisTemplate.opsForValue().setIfAbsent(lockKey, "1", 5, TimeUnit.SECONDS);
        if (Boolean.FALSE.equals(locked)) {
            return Result.error(AvatarMessageConstants.AVATAR_PROCESSING_LOCKED);
        }

        try {
            return avatarService.saveAvatar(file, userId, fileMd5);
        } finally {
            redisTemplate.delete(lockKey);
        }
    }
    
    @PostMapping("/clean")
    public Result cleanGarbageAvatars() {
        try {
            avatarCleanupService.manualCleanGarbageAvatars();
            return Result.success(AvatarMessageConstants.CLEANUP_TASK_EXECUTED);
        } catch (Exception e) {
            log.error("手动清理过期头像文件时发生错误", e);
            return Result.error(AvatarMessageConstants.CLEANUP_TASK_FAILED + ": " + e.getMessage());
        }
    }
}